#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模拟钉钉数据发送脚本
用于测试钉钉预约系统数据同步功能
"""

import requests
import json
from datetime import datetime

# 钉钉数据格式示例 - multipart/form-data 格式（基于实际接收数据）
dingtalk_data = {
    "enddate": ["2025-07-15"],
    "project": ["市场类-灵犀09星-西安科技"],
    "days": ["33"],
    "details": ['[{"rowValue":[{"componentType":"DDSelectField","label":"试验设备","extendValue":{"label":"KM2空间环境模拟器（南通）","key":"option_1RC6ZUC1CFGG0"},"value":"KM2空间环境模拟器（南通）","key":"DDSelectField_X8M7RH50GKW0"},{"componentType":"DDDateRangeField","label":["试验开始日期","试验结束日期"],"value":["2025-06-15","2025-07-15",33],"key":"DDDateRangeField_1FCXOM3L9OLC0"}],"rowNumber":"TableField_22KZDF5V61TS0_KH70QCDRVBK0"}]'],
    "bid": ["202508061002000433466"],
    "depart": ["平台研发部-能源产品部-电池电路组"],
    "type": ["单机"],
    "addr": ["南通"],
    "startdate": ["2025-06-15"],
    #"file": ["LX09太阳毯-热真空试验委托单-1.docx", "LX09太阳毯-热真空试验委托单-2.docx", "LX09太阳毯-热真空试验委托单-3.docx", "LX09太阳毯-热真空试验委托单-4.docx", "LX09太阳毯-热真空试验委托单-5.docx"]
    "file": ["试验委托单_徐博20250724","试验委托单_徐博20250726","灵知07星BCD星太阳电池板热真空试验大纲"]
}


def send_dingtalk_data_multipart(data, base_url="http://localhost:8000"):
    """
    发送钉钉数据到后端API - 使用multipart/form-data格式
    
    Args:
        data: 钉钉数据字典（每个字段都是列表格式）
        base_url: 后端API基础URL
    
    Returns:
        响应结果
    """
    url = f"{base_url}/api/experiment-planning/api/experiment-plans/sync_from_dingtalk/"
    
    # 准备multipart数据
    files = []
    form_data = {}
    
    # 处理普通字段
    for key, value_list in data.items():
        if key != 'file':
            form_data[key] = value_list[0] if value_list else ''
    
    # 处理文件上传
    if 'file' in data and data['file']:
        for filename in data['file']:
            # 尝试不同的文件扩展名
            file_extensions = ['.docx', '.doc']
            file_found = False
            
            for ext in file_extensions:
                file_path = f"d:\\TCTaskSys\\{filename}{ext}"
                try:
                    with open(file_path, 'rb') as f:
                        file_content = f.read()
                    
                    # 根据扩展名设置正确的MIME类型
                    mime_type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' if ext == '.docx' else 'application/msword'
                    files.append(('file', (f"{filename}{ext}", file_content, mime_type)))
                    print(f"成功读取文件: {file_path}")
                    file_found = True
                    break
                except FileNotFoundError:
                    continue
                except Exception as e:
                    print(f"读取文件时出错 {file_path}: {e}")
                    continue
            
            if not file_found:
                print(f"警告: 文件不存在 {filename} (尝试了 .docx 和 .doc 扩展名)")
    
    try:
        print(f"正在发送数据到: {url}")
        print(f"发送表单数据: {json.dumps(form_data, ensure_ascii=False, indent=2)}")
        print(f"发送文件数量: {len(files)}")
        
        response = requests.post(url, data=form_data, files=files, timeout=30)
        
        print(f"响应状态码: {response.status_code}")
        print(f"响应内容: {response.text}")
        
        if response.status_code == 200:
            print("✅ 数据发送成功!")
            return response.json() if response.text else {"status": "success"}
        else:
            print(f"❌ 数据发送失败: {response.status_code}")
            return None
            
    except requests.exceptions.RequestException as e:
        print(f"❌ 请求异常: {e}")
        return None
    except Exception as e:
        print(f"❌ 发生错误: {e}")
        return None

def main():
    """
    主函数 - 发送测试数据
    """
    print("=" * 60)
    print("钉钉数据同步测试脚本")
    print("=" * 60)
    
    # 发送multipart格式数据（模拟钉钉实际发送格式）
    print("\n1. 发送multipart格式数据（模拟钉钉实际格式）:")
    print("-" * 40)
    send_dingtalk_data_multipart(dingtalk_data)
    
        
    print("\n" + "=" * 60)
    print("测试完成!")
    print("=" * 60)

if __name__ == "__main__":
    main()